package com.TestGroupBox;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.Rect;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;

public class GroupBox extends LinearLayout{
	private int mPadding;
	private String mTitle;
	private void intPara()
	{
		mPadding = 10;
		
		this.setPadding(mPadding*2, mPadding*2, mPadding*2, mPadding*2);
	}
	public GroupBox(Context context)
	{
		super(context);
		intPara();
	}
	public GroupBox(Context context, AttributeSet attrs) {
		super(context, attrs);
		intPara();
		
		int resouceId = -1;
		TypedArray typeArray = context.obtainStyledAttributes(attrs,R.styleable.GroupBox);
		
		int N = typeArray.getIndexCount();
		for(int i=0;i<N;i++)
		{
			int attr = typeArray.getIndex(i);
			switch(attr){
				case R.styleable.GroupBox_Title:
					resouceId = typeArray.getResourceId(R.styleable.GroupBox_Title, 0);
					this.mTitle = (String) (resouceId > 0 ? typeArray.getResources().getText(resouceId) : typeArray.getString(R.styleable.GroupBox_Title));
					break;
			}
		}
		typeArray.recycle();
	}
	
	protected void dispatchDraw(Canvas canvas){
		Paint borderPaint = new Paint();
		RectF drawRect = new RectF();
		borderPaint.setARGB(255, 255, 255, 255);
		borderPaint.setAntiAlias(true);
		borderPaint.setStyle(Style.STROKE);
		borderPaint.setStrokeWidth(2);		
		
		int padding = mPadding;
		drawRect.set(0+padding,0+padding,this.getMeasuredWidth()-padding,this.getMeasuredHeight()-padding); 
		canvas.drawRoundRect(drawRect,5,5,borderPaint);
		
		Paint paintPen = new Paint();
		paintPen.setColor(Color.WHITE);
		paintPen.setStyle(Style.FILL);
		paintPen.setTextSize(20);
		
		Rect ret = new Rect();
		paintPen.getTextBounds(mTitle, 0, mTitle.length(), ret);
		int txtX = mPadding*2;
		int txtY = mPadding+ret.height()/2;
		Paint paintBg = new Paint();
		paintBg.setColor(Color.BLACK);
		canvas.drawRect(txtX, txtY-ret.height(), txtX+ret.width(), txtY, paintBg);
		canvas.drawText(mTitle, txtX, txtY, paintPen);
		super.dispatchDraw(canvas);
	}  

}
